package com.momo.support;

import com.momo.configuration.WxProperties;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.context.support.WebApplicationContextUtils;
import weixin.popular.support.TokenManager;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.List;

/**
 * Created by Kagome on 2019/5/24.
 */
@AllArgsConstructor
@WebListener
@EnableConfigurationProperties(WxProperties.class)
public class TokenManagerListenerTest implements ServletContextListener {

    private WxProperties wxProperties;


    @Override
    public void contextInitialized(ServletContextEvent sce) {
        /*WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext())
                .getAutowireCapableBeanFactory().autowireBean(this);*/

        List<WxProperties.WxConfig> mpConfigs = wxProperties.getConfigs();
        mpConfigs.forEach(wxConfig -> {
            //WEB容器 初始化时调用
            TokenManager.init(wxConfig.getAppId(), wxConfig.getSecret());
            String accessToken = TokenManager.getToken(wxConfig.getAppId());
        });
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        //WEB容器  关闭时调用
        TokenManager.destroyed();
    }
}